package org.fuxia.im.core.service.impl;


import org.apache.log4j.Logger;
import org.fuxia.im.core.entries.ECPacket;
import org.fuxia.im.core.entries.ECResponse;
import org.fuxia.im.core.entries.ECSession;
import org.fuxia.im.core.server.ECSessionMananger;
import org.fuxia.im.core.socket.impl.ECNioServer;

public class PacketDispathService extends AbstractService
{
	private static final Logger	logger	= Logger.getLogger(PacketDispathService.class);

	public void service(ECPacket packet)
	{
		ECResponse resp = new ECResponse();
		resp.setStatusCode(200);
		resp.setResponseType("send_result");
		try
		{
			String to = packet.getTo();
			if (to.contains("#"))
			{
				String[] toes = to.split("#");
				for(String toUser:toes){
					sendPacket(toUser, packet) ;
				}
			}
			else
			{
				sendPacket(to,packet);
			}
			writeReponse(packet, resp) ;
		}
		catch (Exception e)
		{
			logger.error(e);
			//no ops
		}
	}
	
	private void sendPacket(String userCode,ECPacket packet) throws Exception {
		ECSession toSession = ECSessionMananger.getInstance().getUserSession(userCode);
		if (toSession != null) {
			ECNioServer.sendPacket(packet, toSession.getChannel());
		}else{
			ECSessionMananger.getInstance().putOfflineMessage(packet);
		}
	}
}
